package com.example.beixiangsuapp.bxs.homepage;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.percent.PercentRelativeLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.beixiangsuapp.R;
import com.example.beixiangsuapp.bxs.homepage.utils.FbLocation;
import com.example.beixiangsuapp.bxs.utils.netutils;
import com.example.beixiangsuapp.bxs.views.PinnedHeaderExpandableAdapter;
import com.example.beixiangsuapp.bxs.views.PinnedHeaderExpandableListView;
import com.recker.flybanner.FlyBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/13.
 */

public class HomeFragment extends Fragment implements View.OnClickListener {
    private View view, head_view, v;
    private PinnedHeaderExpandableListView ex_listView;
    private Map<String, List<Object>> childrenData;
    private PinnedHeaderExpandableAdapter adapter;
    private FlyBanner fly_banner;
    private List<String> groups;
    //是否到底部
    private boolean isLast = false;
    private ArrayList images = new ArrayList<>();
    private PercentRelativeLayout layout_relative;
    private LinearLayout text_1;
    private ImageView image;
    private TextView text_address;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragment, container, false);
        initView();
        initData();
        setData();
        setListener();
        return view;
    }

    private void setListener() {
        text_address.setOnClickListener(this);
        ex_listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isLast && scrollState == SCROLL_STATE_IDLE) {

                    List<Object> objects = new ArrayList<>();
                    for (int i = 1; i < 20; i++) {
                        objects.add("lala" + i);
                    }
                    childrenData.put("first", objects);
                    adapter.notifyDataSetChanged();
                } else {

                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isLast = ((firstVisibleItem + visibleItemCount) == totalItemCount);
                if (firstVisibleItem == 0) {
                    if (fly_banner.getHeight() - getScrollY() == layout_relative.getHeight()) {
                        text_1.setVisibility(View.VISIBLE);
                    } else if (fly_banner.getHeight() - getScrollY() > layout_relative.getHeight()) {
                        text_1.setVisibility(View.GONE);
                    } else if (fly_banner.getHeight() - getScrollY() < layout_relative.getHeight()) {
                        text_1.setVisibility(View.VISIBLE);
                    }
                    if (getScrollY() < (fly_banner.getHeight() * 0.70)) {
                        layout_relative.getBackground().setAlpha(getScrollY());
                    } else {
                        layout_relative.setBackgroundColor(Color.parseColor("#0080ff"));
                    }
                } else {
                    text_1.setVisibility(View.VISIBLE);
                    layout_relative.setBackgroundColor(Color.parseColor("#0080ff"));
                }


            }
        });
    }

    public int getScrollY() {
        View c = ex_listView.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = ex_listView.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }

    private void setData() {
        v = LayoutInflater.from(getContext()).inflate(R.layout.head_view,
                ex_listView, false);
        head_view = LayoutInflater.from(getActivity()).inflate(R.layout.list_head, ex_listView, false);
        fly_banner = head_view.findViewById(R.id.fly_banner);
        ex_listView.addHeaderView(head_view);

        List<Object> objects = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            objects.add("lala" + i);
        }
        childrenData.put("first", objects);
        ex_listView.setAdapter(adapter);
        for (int i = 0; i < childrenData.size(); i++) {
            ex_listView.expandGroup(i);
            adapter.setGroupClickStatus(i, 1);
        }
        getSrcData(3);
    }

    private void initData() {
        groups = new ArrayList<>();
        groups.add("first");
        childrenData = new HashMap<>();
        adapter = new PinnedHeaderExpandableAdapter(childrenData, getActivity(), ex_listView, groups, images);
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getActivity(), "定位权限已关闭，请去手机设置中的权限管理中开启", Toast.LENGTH_SHORT).show();
        } else {
            Location location = baiduMap();
            if (location != null) {
                List<Address> address = getAddress(location);
                Iterator<Address> iterator = address.iterator();
                while (iterator.hasNext()) {
                    Address s = iterator.next();
                    String locality = s.getLocality();
                    text_address.setText(locality);
                }
            }
        }

    }

    private List<Address> getAddress(Location location) {
        List<Address> result = null;
        try {
            if (location != null) {
                Geocoder gc = new Geocoder(getActivity(), Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //获取当前定位
    public Location baiduMap() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        FbLocation fbLocation = new FbLocation(getActivity(), locationManager);
        Location loca = fbLocation.getLngAndLat(getActivity());
        return loca;
    }

    private void initView() {
        text_address = view.findViewById(R.id.address);
        ex_listView = view.findViewById(R.id.ex_listView);
        fly_banner = view.findViewById(R.id.fly_banner);
        layout_relative = view.findViewById(R.id.layout_relative);
        text_1 = view.findViewById(R.id.text_1);
        image = view.findViewById(R.id.image);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String response3 = (String) msg.obj;
                    if (response3 != null) {
                        // json解析
                        try {
                            JSONObject jsonObject = new JSONObject(response3);
                            JSONObject data = jsonObject.getJSONObject("data");
                            JSONArray ImgList = data
                                    .getJSONArray("ImgList");
                            for (int i = 0; i < ImgList.length(); i++) {
                                // 调用工具类
                                String bimgs = ImgList.getString(i);
                                images.add(bimgs);
                            }
                            if (images.size() > 0) {
                                fly_banner.setImagesUrl(images);
                            }

                        } catch (JSONException e) {
                        }

                    }
                    break;
            }
        }
    };

    private void RotateAnimation() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(image, "rotation", 0f, 180f);
        anim.setDuration(100);
        anim.start();
    }

    public void getSrcData(int PlatformId) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("platformId", PlatformId);
        } catch (JSONException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        netutils.getInstance().postToServer("http://120.25.74.56:10082/agent/app/ordersAPP/selectadurl", jsonObject, handler, 1, getActivity());

    }

    @Override
    public void onClick(View v) {
        if (v != null) {
            switch (v.getId()) {
                case R.id.address:
                    RotateAnimation();
                    Intent intent = new Intent(getActivity(), ChooseCityActivity.class);
                    intent.putExtra("cityName", text_address.getText().toString());
                    startActivityForResult(intent, 1);
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case 1:
                    String add = data.getStringExtra("cityName");
                    text_address.setText(add);
                    break;
            }
        }
    }
}
